import { _decorator, Component, Node } from 'cc';
import {TileMapManager} from "../Tile/TileMapManager";
import {createUINode} from "../../Utils";
import Levels, {ILevel} from "../../Levels";
import {TILE_HEIGHT, TILE_WIDTH} from "../Tile/TileManager";
import DataManager from "../../Runtime/DataManager";
import EventManager from "../../Runtime/EventManager";
import {EVENT_ENUM} from "../../Enums";
import {PlayerManager} from "../Player/PlayerManager";
const { ccclass, property } = _decorator;

@ccclass('BattleManager')
export class BattleManager extends Component {
    level: ILevel;
    stage: Node;
    start() {
        this.generateState();

        this.initLevel();
    }

    onLoad() {
        EventManager.Instance.on(EVENT_ENUM.NEXT_LEVEL, this.nextLevel, this);
    }

    onDestroy() {
        EventManager.Instance.off(EVENT_ENUM.NEXT_LEVEL, this.nextLevel);
    }

    generateState() {
        this.stage = createUINode();
        this.stage.setParent(this.node);
    }
    initLevel() {
        const level = Levels[`level${DataManager.Instance.levelIndex}`];

        if(level) {
            this.clearLevel();

            this.level = level;
            DataManager.Instance.mapInfo = level.mapInfo;
            DataManager.Instance.mapRowCount = level.mapInfo.length;
            DataManager.Instance.mapColumnCount = level.mapInfo[0].length;
            this.generateTileMap();

            this.generatePlayer();
        }
    }

    nextLevel() {
        DataManager.Instance.levelIndex ++;
        this.initLevel();
    }

    clearLevel() {
        this.stage.destroyAllChildren();
        DataManager.Instance.reset();
    }

    generatePlayer() {
        const player = createUINode();
        player.setParent(this.stage);
        const playerManager = player.addComponent(PlayerManager);
        playerManager.init();
    }

    generateTileMap() {
        const tileMap = createUINode();
        tileMap.setParent(this.stage);
        const tileMapManager = tileMap.addComponent(TileMapManager);
        tileMapManager.init();

        this.adaptPos();
    }

    adaptPos() {
        const disX = DataManager.Instance.mapRowCount * TILE_WIDTH / 2;
        const disY = DataManager.Instance.mapColumnCount * TILE_HEIGHT / 2 + 80;
        this.stage.setPosition(-disX, disY);
    }


}

